package com.mt.mtbletools;

import java.util.List;
import com.mt.help.GlobalVariable;
import com.mt.model.UuidAndName;
import com.mt.mtbletools.R;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.base.MTBeacon4Base;
import com.mt.sdk.ble.base.MTBeacon4Base.ReadInfsCallBack;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.ble.model.MTBeaconInfModel;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class MTBeacon4Activity extends Activity {
	private GlobalVariable mGlobalVariable;
	private MTBLEManager manger;
	private MTBeacon4Base mBle;
	private Handler handl = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_mtbeacon4);

		mGlobalVariable = GlobalVariable.getinstance();
		manger = mGlobalVariable.getBleManger();

		mBle = new MTBeacon4Base(getApplicationContext(), manger);

		getPulicDatas();

		getDefaultDatas();

		initView();

		startConnect();
	}

	// 获取全局数据
	private List<UuidAndName> uuids;

	private void getPulicDatas() {
		uuids = mGlobalVariable.getUuids();
	}

	// 获取传送过来的数据
	private MTBLEDevice device;
	private int index;
	private void getDefaultDatas() {
		index = getIntent().getIntExtra(ScanFragment.SELECTDEVICE, -1);
		if (index == -1) {
			finish();
			return;
		}
		if (mGlobalVariable.getDeviceList().size() == 0) {
			finish();
			return;
		}
		device = mGlobalVariable.getDeviceList().get(index);
	}

	// 初始化控件
	private Button goback_btn;
	private TextView device_name_txt;
	private Spinner beaconid_spinner;
	private EditText major_edit;
	private EditText minor_edit;
	private EditText measur_edit;
	private EditText weight_edit;
	private TextView uuid_txt;
	private Spinner uuid_spinner;
	private Button privateparamscfg_btn;
	private EditText sendhz_edit;
	private Spinner sendpower_spinner;
	private CheckBox pwd_enable_check;
	private EditText newpwd_edit;
	private Button publicparamscfg_btn;
	private TextView beacon_version_txt;
	private Button setundeverlop_btn;

	private ArrayAdapter<String> sendpower_adapter;
	private ArrayAdapter<UuidAndName> uuid_adapter;

	private static final String BEACONSELECT_SELCET[] = { "1", "2", "3"};//, "4", "5", "6", "7", "8",};
	private ArrayAdapter<String> beaconselect_adapter;

	private void initView() {
		goback_btn = (Button) findViewById(R.id.goback_btn);
		device_name_txt = (TextView) findViewById(R.id.device_name_txt);
		beaconid_spinner = (Spinner) findViewById(R.id.beaconid_spinner);
		major_edit = (EditText) findViewById(R.id.major_edit);
		minor_edit = (EditText) findViewById(R.id.minor_edit);
		measur_edit = (EditText) findViewById(R.id.measur_edit);
		weight_edit = (EditText) findViewById(R.id.weight_edit);
		uuid_txt = (TextView) findViewById(R.id.uuid_txt);
		uuid_spinner = (Spinner) findViewById(R.id.uuid_spinner);
		privateparamscfg_btn = (Button) findViewById(R.id.privateparamscfg_btn);
		sendhz_edit = (EditText) findViewById(R.id.sendhz_edit);
		sendpower_spinner = (Spinner) findViewById(R.id.sendpower_spinner);
		pwd_enable_check = (CheckBox) findViewById(R.id.pwd_enable_check);
		newpwd_edit = (EditText) findViewById(R.id.newpwd_edit);
		publicparamscfg_btn = (Button) findViewById(R.id.publicparamscfg_btn);
		beacon_version_txt = (TextView) findViewById(R.id.beacon_version_txt);
		setundeverlop_btn = (Button) findViewById(R.id.setundeverlop_btn);

		device_name_txt.setText(device.getDevice().getName());

		sendpower_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				MTBeacon4Base.SENDPOWERNAME);
		sendpower_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sendpower_spinner.setAdapter(sendpower_adapter);

		uuid_adapter = new ArrayAdapter<UuidAndName>(this, android.R.layout.simple_spinner_item, uuids);
		uuid_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		uuid_spinner.setAdapter(uuid_adapter);

		beaconselect_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				BEACONSELECT_SELCET);
		beaconselect_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		beaconid_spinner.setAdapter(beaconselect_adapter);

		uuid_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				uuid_txt.setText(uuids.get(position).getUuid());
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		beaconid_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (privateinfs == null) {
					return;
				}

				major_edit.setText("" + privateinfs[position].getMajor());
				minor_edit.setText("" + privateinfs[position].getMinor());
				measur_edit.setText("" + privateinfs[position].getMeasuedPower());
				weight_edit.setText("" + privateinfs[position].getWeight());
				uuid_spinner.setSelection(position);

				for (int i = 0; i < uuids.size(); i++) {
					UuidAndName uuid = uuids.get(i);
					if (uuid.getUuid().equals(privateinfs[position].getBeaconUUID())) {
						uuid_spinner.setSelection(i);
					}
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {

			}
		});

		goback_btn.setOnClickListener(myOnClickListener);
		privateparamscfg_btn.setOnClickListener(myOnClickListener);
		publicparamscfg_btn.setOnClickListener(myOnClickListener);
		setundeverlop_btn.setOnClickListener(myOnClickListener);
	}

	// 按钮监听
	private OnClickListener myOnClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (v == goback_btn) {
				finish();
				return;
			}

			if (v == privateparamscfg_btn) {
				final MTBeaconInfModel deviceinf = getPrivateParamters();

				if (deviceinf == null) {
					return;
				}

				boolean result = mBle.setPrivateParamters(device, mGlobalVariable.getMixedvalues().getPwd(), deviceinf, new MTBeacon4Base.BaseCallBack() {

					@Override
					public void onSuccess() {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
						privateinfs[deviceinf.getBeaconid()] = deviceinf;
						System.out.println("onSuccess");
					}

					@Override
					public void onFail(ErroCode erro) {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
						System.out.println("onFail->" + erro.toString());
						Toast.makeText(MTBeacon4Activity.this, erro.getMsg(), Toast.LENGTH_LONG).show();
					}
				});

				if (result) {
					pd = ProgressDialog.show(MTBeacon4Activity.this, "wait", "正在设置私有参数", true, true,
							new OnCancelListener() {

						@Override
						public void onCancel(DialogInterface dialog) {
							mBle.disConnect();
						}
					});
				}

				return;
			}

			if (v == publicparamscfg_btn) {

				final MTBeaconInfModel deviceinf = getPublicParamters();

				if (deviceinf == null) {
					return;
				}

				boolean result = mBle.setPublicParamters(device, mGlobalVariable.getMixedvalues().getPwd(), deviceinf, new MTBeacon4Base.BaseCallBack() {

					@Override
					public void onSuccess() {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
//						if(deviceinf.getNewpwd() != null){
//							if(deviceinf.getNewpwd().length() == 0){
//								mGlobalVariable.getMixedvalues().getPwd() = null;
//							}else{
//								mGlobalVariable.getMixedvalues().getPwd() = deviceinf.getNewpwd();
//							}
//						}
						System.out.println("onSuccess");
					}

					@Override
					public void onFail(ErroCode erro) {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
						System.out.println("onFail->" + erro.toString());
						Toast.makeText(MTBeacon4Activity.this, erro.getMsg(), Toast.LENGTH_LONG).show();
					}
				});

				if (result) {
					pd = ProgressDialog.show(MTBeacon4Activity.this, "wait", "正在设置公共参数", true, true,
							new OnCancelListener() {

						@Override
						public void onCancel(DialogInterface dialog) {
							mBle.disConnect();
						}
					});
				}
				return;
			}

			if (v == setundeverlop_btn) {

				boolean result = mBle.setUndevelop(device, mGlobalVariable.getMixedvalues().getPwd(), new MTBeacon4Base.BaseCallBack() {

					@Override
					public void onSuccess() {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
						finish();
						System.out.println("onSuccess");
					}

					@Override
					public void onFail(ErroCode erro) {
						if ((pd != null) && (pd.isShowing())) {
							pd.dismiss();
						}
						System.out.println("onFail->" + erro.toString());
						Toast.makeText(MTBeacon4Activity.this, erro.getMsg(), Toast.LENGTH_LONG).show();
					}
				});

				if (result) {
					pd = ProgressDialog.show(MTBeacon4Activity.this, "wait", "正在临时部署", true, true,
							new OnCancelListener() {

						@Override
						public void onCancel(DialogInterface dialog) {
							mBle.disConnect();
						}
					});
				}
				return;
			}
		}
	};

	// 连接
	private ProgressDialog pd;

	private void startConnect() {
		pd = ProgressDialog.show(MTBeacon4Activity.this, "wait", "正在同步数据", true, true, new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				mBle.disConnect();
			}
		});

		readAllBeaconInf();
	}

	// 获取常用参数
	private MTBeaconInfModel getPrivateParamters() {

		MTBeaconInfModel beaconinf = new MTBeaconInfModel();

		// 检查调整数据是否符合格式
		beaconinf.setBeaconid(beaconid_spinner.getSelectedItemPosition()); // 设备编号

		if (major_edit.getText().length() == 0) { // 判断major是否合理
			getFocus(major_edit);
			return null;
		}
		beaconinf.setMajor(Integer.parseInt(major_edit.getText().toString()));
		if ((beaconinf.getMajor() < 0) || (beaconinf.getMajor() > 65535)) {
			Toast.makeText(getApplicationContext(), "major不能为空", Toast.LENGTH_LONG).show();
			getFocus(major_edit);
			return null;
		}

		if (minor_edit.getText().length() == 0) { // 判断minor是否合理
			Toast.makeText(getApplicationContext(), "minor不能为空", Toast.LENGTH_LONG).show();
			getFocus(minor_edit);
			return null;
		}
		beaconinf.setMinor(Integer.parseInt(minor_edit.getText().toString()));
		if ((beaconinf.getMinor() < 0) || (beaconinf.getMinor() > 65535)) {
			Toast.makeText(getApplicationContext(), "minor格式错误", Toast.LENGTH_LONG).show();
			getFocus(minor_edit);
			return null;
		}

		if (measur_edit.getText().length() == 0) { // 判断Measure是否合理
			Toast.makeText(getApplicationContext(), "measur不能为空", Toast.LENGTH_LONG).show();
			getFocus(measur_edit);
			return null;
		}
		beaconinf.setMeasuedPower(Integer.parseInt(measur_edit.getText().toString()));
		if ((beaconinf.getMeasuedPower() < 0) || (beaconinf.getMeasuedPower() > 99)) {
			Toast.makeText(getApplicationContext(), "measur格式错误", Toast.LENGTH_LONG).show();
			getFocus(measur_edit);
			return null;
		}

		if (weight_edit.getText().length() == 0) { // 判断weight是否合理
			Toast.makeText(getApplicationContext(), "weight不能为空", Toast.LENGTH_LONG).show();
			getFocus(weight_edit);
			return null;
		}
		beaconinf.setWeight(Integer.parseInt(weight_edit.getText().toString()));
		if ((beaconinf.getWeight() < 0) || (beaconinf.getWeight() > 10)) {
			Toast.makeText(getApplicationContext(), "weight格式错误", Toast.LENGTH_LONG).show();
			getFocus(weight_edit);
			return null;
		}

		beaconinf.setBeaconUUID(uuid_txt.getText().toString());

		return beaconinf;
	}

	// 获取公共参数
	private MTBeaconInfModel getPublicParamters() {
		MTBeaconInfModel beaconinf = new MTBeaconInfModel();

		if (sendhz_edit.getText().length() == 0) { // 判断广播频率是否合理
			Toast.makeText(getApplicationContext(), "广播频率不能为空", Toast.LENGTH_LONG).show();
			getFocus(sendhz_edit);
			return null;
		}
		beaconinf.setSendhz(Integer.parseInt(sendhz_edit.getText().toString()));
		if ((beaconinf.getSendhz() < 100) || (beaconinf.getSendhz() > 2000)) {
			Toast.makeText(getApplicationContext(), "广播频率格式错误", Toast.LENGTH_LONG).show();
			getFocus(sendhz_edit);
			return null;
		}

		if (pwd_enable_check.isChecked()) {
			System.out.println("lenght->" + newpwd_edit.getText().length());
			if (!((newpwd_edit.getText().length() == 6) || (newpwd_edit.getText().length() == 0))) {
				Toast.makeText(getApplicationContext(), "请输入新密码", Toast.LENGTH_LONG).show();
				getFocus(newpwd_edit);
				return null;
			}
			beaconinf.setNewpwd(newpwd_edit.getText().toString());
		} else {
			beaconinf.setNewpwd(null);
		}

		beaconinf.setSendpower(sendpower_spinner.getSelectedItemPosition());

		return beaconinf;
	}

	// 控件获取焦点
	private void getFocus(View v) {
		v.setFocusable(true);
		v.setFocusableInTouchMode(true);
		v.requestFocus();
		v.requestFocusFromTouch();
	}

	// 读取所有beacon信息
	private MTBeaconInfModel[] privateinfs = new MTBeaconInfModel[] { new MTBeaconInfModel(), new MTBeaconInfModel(),
			new MTBeaconInfModel(), new MTBeaconInfModel(), new MTBeaconInfModel(), new MTBeaconInfModel(),
			new MTBeaconInfModel(), new MTBeaconInfModel()};

	private boolean readAllBeaconInf() {
		mBle.readAllInf(device, mGlobalVariable.getMixedvalues().getPwd(), new ReadInfsCallBack() {

			@Override
			public void onSuccess(MTBeaconInfModel publicinf, MTBeaconInfModel[] privateinf) {
				System.out.println("onSuccess");

				MTBeacon4Activity.this.privateinfs = privateinf;

				if ((pd != null) && (pd.isShowing())) {
					pd.dismiss();
				}
				
				for (int i=0; i<privateinf.length; i++) {
					boolean findit = false;
					for (UuidAndName uuid : uuids) {
						if(uuid.getUuid().equals(privateinf[i].getBeaconUUID())){
							findit = true;
							break;
						}
					}
					if(!findit){
						uuids.add(new UuidAndName("未命名", privateinf[i].getBeaconUUID()));
					}
				}
				uuid_adapter.notifyDataSetChanged();

				sendhz_edit.setText("" + publicinf.getSendhz());
				sendpower_spinner.setSelection(publicinf.getSendpower());
				beacon_version_txt.setText(getResources().getString(R.string.versionnum) + publicinf.getVersion());

				int selectindex = device.getBeaconid();
				if(selectindex>=8){
					selectindex = 0;
				}
				
				major_edit.setText("" + privateinf[selectindex].getMajor());
				minor_edit.setText("" + privateinf[selectindex].getMinor());
				measur_edit.setText("" + privateinf[selectindex].getMeasuedPower());
				weight_edit.setText("" + privateinf[selectindex].getWeight());

				boolean findit = false; // 显示uuid
				for (int i = 0; i < uuids.size(); i++) {
					UuidAndName uuid = uuids.get(i);
					if (uuid.getUuid().equals(privateinf[selectindex].getBeaconUUID())) {
						uuid_spinner.setSelection(i);
						findit = true;
					}
				}
				if (!findit) {
					uuids.add(new UuidAndName("未命名", privateinf[selectindex].getBeaconUUID()));
					uuid_adapter.notifyDataSetChanged();
					uuid_spinner.setSelection(uuids.size() - 1);
				}
			}

			@Override
			public void onFail(ErroCode erro) {
				if ((pd != null) && (pd.isShowing())) {
					pd.dismiss();
				}
				finish();
				System.out.println("onFail->" + erro.toString());
				Toast.makeText(getApplicationContext(), erro.getMsg(), Toast.LENGTH_LONG).show();
			}
		});

		return true;
	}
}
